#!/usr/bin/env python3
import json
import urllib.parse
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

clients = []
class SimpleChat(WebSocket):

    def parseRole(self):
        return urllib.parse.parse_qs(self.request.path[2:])['role'][0]

    def isController(self):
        return self.parseRole() == 'controller'

    def isDevice(self):
        return self.parseRole() == 'device'

    def handleMessage(self):
        for client in clients:
            if client != self and client.isDevice():
                client.sendMessage(
                    json.dumps(
                        {
                            'event'     : 'message',
                            'address'   : self.address[0],
                            'port'      : self.address[1],
                            'role'      : self.parseRole(),
                            'data'      : json.loads(self.data)
                        }
                    )
                )

    def handleConnected(self):
       print(self.address, 'connected', ' role: ' + self.parseRole())
       for client in clients:
           if client != self:
                client.sendMessage(
                    json.dumps(
                        {
                            'event'     : 'connected',
                            'address'   : self.address[0],
                            'port'      : self.address[1],
                            'role'      : self.parseRole()
                        }
                    )
                )
       clients.append(self)

    def handleClose(self):
       clients.remove(self)
       print(self.address, 'closed', ' role: ' + self.parseRole())
       for client in clients:
          print(self.address[0] + u' - disconnected', ' role: ' + self.parseRole())
          client.sendMessage(
                    json.dumps(
                        {
                            'event'     : 'disconnected',
                            'address'   : self.address[0],
                            'port'      : self.address[1],
                            'role'      : self.parseRole()
                        }
                    )
                )


server = SimpleWebSocketServer('192.168.50.152', 5000, SimpleChat)
server.serveforever()

